package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"gorm.io/gorm"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/proto"
	"mxshop_srvs/user_srv/global"
)

// Paginate 分页
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

// BrandList 品牌列表
func (svc *GoodsServer) BrandList(ctx context.Context, request *proto.BrandFilterRequest) (*proto.BrandListResponse, error) {
	brandListResponse := proto.BrandListResponse{}
	var brands []model.Brands
	result := global.DB.Find(&brands)
	if result.Error != nil {
		return nil, result.Error
	}
	result = global.DB.Scopes(Paginate(int(request.Pages), int(request.PagePerNums))).Find(&brandListResponse)
	if result.Error != nil {
		return nil, result.Error
	}
	var total int64
	global.DB.Model(&model.Brands{}).Count(&total)
	brandListResponse.Total = int32(total)
	var brandResponse []*proto.BrandInfoResponse
	for _, brand := range brands {
		brandResponse = append(brandResponse, &proto.BrandInfoResponse{
			Id:   brand.ID,
			Name: brand.Name,
			Logo: brand.Logo,
		})
	}
	brandListResponse.Data = brandResponse
	return &brandListResponse, result.Error
}

// CreateBrand 新建品牌
func (svc *GoodsServer) CreateBrand(ctx context.Context, request *proto.BrandRequest) (*proto.BrandInfoResponse, error) {

	// 检查品牌是否已存在
	if result := global.DB.Where("name = ?", request.Name).First(&model.Brands{}); result.RowsAffected > 0 {
		return nil, status.Errorf(codes.InvalidArgument, "品牌已存在!")
	}

	// 创建新的品牌
	brand := &model.Brands{
		Name: request.Name,
		Logo: request.Logo,
	}
	global.DB.Save(brand)

	return &proto.BrandInfoResponse{Id: brand.ID}, nil
}

func (svc *GoodsServer) DeleteBrand(ctx context.Context, request *proto.BrandRequest) (*emptypb.Empty, error) {
	if result := global.DB.Delete(&model.Brands{}, request.Id); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在!")
	}
	return &emptypb.Empty{}, nil
}

func (svc *GoodsServer) UpdateBrand(ctx context.Context, request *proto.BrandRequest) (*emptypb.Empty, error) {
	brand := &model.Brands{}
	// 检查品牌是否不存在
	if result := global.DB.Where("id = ?", request.Id).First(&model.Brands{}); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "品牌不存在!")
	}

	if request.Name != "" {
		brand.Name = request.Name
	}
	if request.Logo != "" {
		brand.Logo = request.Logo
	}
	result := global.DB.Save(brand)

	return &emptypb.Empty{}, result.Error
}
